package com.ruoyi.ommpuser.wxutils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.ommpuser.wxutils.constant.WeChatAppConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class WxUtil {

    @Value("${app.appId}")
    private String appid;
    @Value("${app.secret}")
    private String secret;

    public String getWxOpenId(String code) throws Exception {
        //微信登录方法,请求接口https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String message = OkHttpUtils.builder().url(WeChatAppConstants.LOGINURL)
                // 有参数的话添加参数，可多个
                .addParam("appid", appid)
                .addParam("secret", secret)
                .addParam("js_code", code)
                .addParam("grant_type", "authorization_code")
                //.addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                .async();
        // .sync();
        //message转map
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        String openid = String.valueOf(map.get("openid"));
        if (null==openid){
            throw  new Exception("小程序登录失败，请联系管理员");
        }
        return openid;
    }
}
